package cn.softgame.jserver.connector.udp;

import java.io.IOException;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;

/**
 * UDP数据包读和发送处理类
 * @author xuquan
 * 日期:2013-5-28
 */
public class UDPHandler implements Runnable{

	private DatagramChannel dc;
	private SelectionKey key;
	private final static int READING=0,SENDING=1;
	private int state=READING;
	private SocketAddress address=null;
	
	public UDPHandler(SelectionKey key,DatagramChannel dc){
		this.dc=dc;
		this.key=key;
	}
	
	@Override
	public void run() {
		try {
			if(state==READING)
				read();
			else if(state==SENDING)
				send();
		} catch (Exception e) {
			e.printStackTrace();
			close(dc);
			key.cancel();
		}
	}

	private void read(){
		try {
			byte[] array = new byte[512];
			ByteBuffer buffer = ByteBuffer.wrap(array);
			address = dc.receive(buffer);
			String str = new String(array);
			System.out.println("handlePendingReads() :" + str);
		    state = SENDING;
		    key.interestOps(SelectionKey.OP_WRITE);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void send() {
		try {
			String req = "come back";
			ByteBuffer buffer1 = ByteBuffer.wrap(req.getBytes());
			dc.send(buffer1, address);
			System.out.println("send :" + req);
			state=READING;
			key.interestOps(SelectionKey.OP_READ);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void close(DatagramChannel dc){
		try {
			if(dc!=null){
				dc.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
